const Koa = require('koa')
const cors = require('koa2-cors')
// const { koaBody } = require('koa-body')
const bodyparser = require('koa-bodyparser')
const session = require('koa-session');
const errHandle = require('./errHandler')

const app = new Koa()

app.keys = ['some secret hurr'] // 签名

const CONFIG = {
    key: 'sessionId', /** (string) cookie key (default is koa.sess) */
    /** (number || 'session') maxAge in ms (default is 1 days) */
    /** 'session' will result in a cookie that expires when session/browser is closed */
    /** Warning: If a session cookie is stolen, this cookie will never expire */
    maxAge: 86400000, // 超时时间
    // autoCommit: true, /** (boolean) automatically commit headers (default true) */
    // overwrite: true, /** (boolean) can overwrite or not (default true) */
    httpOnly: true, /** 只能由服务器端修改 */
    signed: true, /** (boolean) signed or not (default true) */
    // rolling: false, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */
    // renew: false, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/
    // secure: true, /** (boolean) secure cookie*/
    // sameSite: null, /** (string) session cookie sameSite options (default null, don't set it) */
};

app.use(session(CONFIG, app));
const userRouter = require('../router/user.route')

// app.use(ctx => {
//     // ignore favicon
//     if (ctx.path === '/favicon.ico') return;
//     console.log('访问成功')
//     let n = ctx.session.views || 0;
//     ctx.session.views = ++n;
//     ctx.body = n + ' views';
// });

// app.use(koaBody()) // 一定要在路由引入之前
app.use(bodyparser())
app.use(cors()); // 解决跨域问题
app.use(userRouter.routes()) // 启动路由
app.use(userRouter.allowedMethods()) // 允许任何请求(get,post,put)
// 在最后可以做一个统一的错误处理
app.on('error', errHandle)

module.exports = app